package cn.linzelin.utils;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;


/**
 * Druid方式的链接池获取
 * @author 君未洋
 */
public class JDBCUtils_Druid {

    private static DataSource ds = null;
    static {
        //使用静态代码块来初始化内存
        try{
            InputStream is = JDBCUtils_Druid.class.getClassLoader().getResourceAsStream("druid.properties");
            Properties properties = new Properties();
            properties.load(is);
            //创建数据源
            ds = BasicDataSourceFactory.createDataSource(properties);
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取数据连接方法
     * @return 返回对应的数据连接
     * @throws SQLException 抛出sql异常
     */
    public static Connection getConnection() throws SQLException{
        return ds.getConnection();
    }

    /**
     * 释放资源
     */
    public static void close(Statement stmt, Connection conn) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 释放资源方法
     */
    public static void close(ResultSet rs, Statement stmt, Connection conn) {
        close(stmt,conn);
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
